﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 射线命中墙反射代码
/// </summary>
public class ReflectShoot : MonoBehaviour
{
    public LineRenderer lineRenderer = null;

    [Range(0,50)]
    public int reflectionCount = 3;
    [Range(0,500)]
    public float maxLen = 100;

    void Update()
    {
        var ray = new Ray(transform.position, transform.forward);

        lineRenderer.positionCount = 1;
        lineRenderer.SetPosition(0, transform.position);
        float remainingLength = maxLen;
        RaycastHit hit;
        for (int i = 0; i < reflectionCount; i++)
        {
            if (Physics.Raycast(ray.origin, ray.direction, out hit, remainingLength))
            {
                lineRenderer.positionCount += 1;
                lineRenderer.SetPosition(lineRenderer.positionCount - 1, hit.point);
                remainingLength -= Vector3.Distance(ray.origin, hit.point);
                if (!hit.collider.CompareTag("Mirror"))
                    break;

                var dir = Vector3.Reflect(ray.direction, hit.normal);
                ray = new Ray(hit.point, dir);
            }
            else
            {
                lineRenderer.positionCount += 1;
                lineRenderer.SetPosition(lineRenderer.positionCount - 1, ray.origin + ray.direction * remainingLength);
            }
        }
    }
}